import Vue from "vue";
let _instanceOf = (_constructor) => {
    return function(o) {
        return o instanceof _constructor;
    };
};

Vue.component("remote-script", {
    render: function(createElement) {
        var self = this;
        return createElement("script", {
            attrs: {
                type: "text/javascript",
                src: this.src,
            },
            on: {
                load: function(event) {
                    self.$emit("load", event);
                },
                error: function(event) {
                    self.$emit("error", event);
                },
                readystatechange: function(event) {
                    if (this.readyState == "complete") {
                        self.$emit("load", event);
                    }
                },
            },
        });
    },
    props: {
        src: {
            type: String,
            required: true,
        },
    },
});

Vue.prototype.$broadcast = function(event) {
    // 获取传入事件的类型，判断是否为字符串
    var isSource = typeof event === "string";

    // 校正 event 的值，当接受 event 的类型为字符串时就直接使用，如果不是字符串就使用 event 上的 name 属性
    event = isSource ? event : event.name;

    // if no child has registered for this event,
    // then there's no need to broadcast.
    // 如果当前组件的子组件没有注册该事件，就直接返回，并不用 broadcast
    //console.log(this._events);
    if (this._events && !this._events[event]) return;

    // 获取当前组件的子组件
    var children = this.$children;

    // 将函数接受的参数转换成数组
    var args = Array.prototype.slice.call(arguments);

    // 如果传入事件为字符串
    /* if (isSource) {
                        // use object event to indicate non-source emit
                        // on children
                        // 根据传入的事件名称的参数组装成 object
                        args[0] = { name: event, source: this };
                    } */

    // 循环子组件
    for (var i = 0, l = children.length; i < l; i++) {
        var child = children[i];

        // 在每个子组件中调用 $emit 触发事件
        var shouldPropagate = child.$emit.apply(child, args);

        // 判断调用 $emit 返回的值是否为 true
        if (shouldPropagate) {
            // 如果调用 $emit 返回的值为 true，就递归孙子组件继续广播
            child.$broadcast.apply(child, args);
        }
    }

    // 最后返回当前组件的实例
    return this;
};

Vue.prototype.$dispatch = function() {
    //console.log(event);
    // 首先执行 $emit 触发事件，将返回值保存在 shouldPropagate 中
    var shouldPropagate = this.$emit.apply(this, arguments);

    // 如果首次执行的 $emit 方法返回的值不是 true 就直接返回
    // 如果返回值不是 true 就说明组件逻辑不希望事件继续往父组件进行传递
    if (!shouldPropagate) return;

    // 如果首次执行 $emit 方法返回值是 true 就获取当前组件的 parent 组件实例
    var parent = this.$parent;

    // 将函数接受的参数转换成数组
    var args = Array.prototype.slice.call(arguments);

    // use object event to indicate non-source emit on parents
    // 根据传入的事件名称的参数组装成 object
    //args[0] = { name: event, source: this };

    // 循环知道组件的父组件
    while (parent) {
        // 在父组件中执行 $emit 触发事件
        //console.log(event, args);
        shouldPropagate = parent.$emit.apply(parent, args); //parent.$emit.apply(parent, args);

        // 如果父组件 $emit 返回的是 true 就继续递归祖父组件，否则就停止循环
        parent = shouldPropagate ? parent.$parent : null;
    }

    // 最后返回当前组件实例
    return this;
};

class Extend {
    constructor() {
        return this;
    }
    extend(t, p) {
        t = t || {};
        for (let n in p) t[n] = p[n];
        return t;
    }
    setFontSize(num) {
        num = num || 16;
        var iWidth = (document.documentElement || document.body).clientWidth,
            iHeight = (document.documentElement || document.body).clientHeight,
            fontSize =
            (window.orientation &&
                (window.orientation === 90 || window.orientation === -90)) ||
            iHeight < iWidth ?
            iHeight / num :
            iWidth / num;
        window.baseFontSize = fontSize;
        document.getElementsByTagName("html")[0].style.fontSize =
            fontSize.toFixed(2) + "px";
        return fontSize;
    }
    rgb() {
        //rgb颜色随机
        var r = Math.floor(Math.random() * 256);
        var g = Math.floor(Math.random() * 256);
        var b = Math.floor(Math.random() * 256);
        var rgb = "(" + r + "," + g + "," + b + ")";
        return rgb;
    }
    isArray(obj) {
        return (
            (Array.isArray || _instanceOf(Array))(obj) && typeof obj !== "string"
        );
    }
    dateFormate(d, pattern) {
        d = d ? new Date(d) : new Date();
        pattern = pattern || "yyyy-MM-dd";
        var y = d.getFullYear().toString(),
            o = {
                M: d.getMonth() + 1,
                d: d.getDate(),
                h: d.getHours(),
                m: d.getMinutes(),
                s: d.getSeconds(),
            };
        pattern = pattern.replace(/(y+)/gi, function(a, b) {
            return y.substr(4 - Math.min(4, b.length));
        });
        for (var i in o) {
            pattern = pattern.replace(new RegExp("(" + i + "+)", "g"), function(
                a,
                b
            ) {
                return o[i] < 10 && b.length > 1 ? "0" + o[i] : o[i];
            });
        }
        return pattern;
    }
    getTime(a, c) {
        c = c || a;
        var d = Math.floor(a % 60),
            e = Math.floor((a / 60) % 60),
            g = Math.floor(a / 3600),
            h = Math.floor((c / 60) % 60),
            k = Math.floor(c / 3600);
        if (isNaN(a) || Infinity === a) g = e = d = "-";
        g = 0 < g || 0 < k ? g + ":" : "";
        return (
            g +
            (((g || 10 <= h) && 10 > e ? "0" + e : e) + ":") +
            (10 > d ? "0" + d : d)
        );
    }
    timeago(dateTimeStamp) {
        //dateTimeStamp是一个时间毫秒，注意时间戳是秒的形式，在这个毫秒的基础上除以1000，就是十位数的时间戳。13位数的都是时间毫秒。
        var minute = 1000 * 60; //把分，时，天，周，半个月，一个月用毫秒表示
        var hour = minute * 60;
        var day = hour * 24;
        var week = day * 7;
        //var halfamonth = day * 15;
        var month = day * 30;
        var now = new Date().getTime(); //获取当前时间毫秒
        var diffValue = now - dateTimeStamp; //时间差
        var result = "";

        if (diffValue < 0) {
            return;
        }
        var minC = diffValue / minute; //计算时间差的分，时，天，周，月
        var hourC = diffValue / hour;
        var dayC = diffValue / day;
        var weekC = diffValue / week;
        var monthC = diffValue / month;
        if (monthC >= 1 && monthC <= 3) {
            result = " " + parseInt(monthC) + "月前";
        } else if (weekC >= 1 && weekC <= 3) {
            result = " " + parseInt(weekC) + "周前";
        } else if (dayC >= 1 && dayC <= 6) {
            result = " " + parseInt(dayC) + "天前";
        } else if (hourC >= 1 && hourC <= 23) {
            result = " " + parseInt(hourC) + "小时前";
        } else if (minC >= 1 && minC <= 59) {
            result = " " + parseInt(minC) + "分钟前";
        } else if (diffValue >= 0 && diffValue <= minute) {
            result = "刚刚";
        } else {
            var datetime = new Date();
            datetime.setTime(dateTimeStamp);
            var Nyear = datetime.getFullYear();
            var Nmonth =
                datetime.getMonth() + 1 < 10 ?
                "0" + (datetime.getMonth() + 1) :
                datetime.getMonth() + 1;
            var Ndate =
                datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
            result = Nyear + "-" + Nmonth + "-" + Ndate;
        }
        return result;
    }
    fixNumber(v, max) {
        return parseFloat(v) >= max ? max - 1 + "+" : v;
    }
    isEmptyObject(obj) {
        for (var name in obj) {
            return false;
        }
        return true;
    }
}
export default new Extend();